<template>
  <div>
    <p>
      <button @click="add()" class="btn btn-white btn-default btn-round">
        <i class="ace-icon fa glyphicon-plus"></i>
        新增
      </button>
      &nbsp;
      <button @click="list()" class="btn btn-white btn-default btn-round">
        <i class="ace-icon fa fa-refresh"></i>
        刷新
      </button>
    </p>
    <Pagination ref="pagination" :list="list"></Pagination>
    <div class="row">
      <div v-for="course in courses" class="col-md-2">
        <div class="thumbnail search-thumbnail">
          <img v-show="!course.image" src="https://th.wallhaven.cc/small/3z/3z32j3.jpg"/>
          <img v-show="course.image" v-bind:src="course.image"/>
          <div class="caption">
            <div class="clearfix">
              <span class="pull-right label label-primary info-label">
                {{ $filter.optionKVArray($Enums.COURSE_LEVEL_ARRAY, course.level) }}
              </span>&nbsp;
              <span class="pull-right label label-primary info-label">
                {{ $filter.optionKVArray($Enums.COURSE_CHARGE_ARRAY, course.charge) }}
              </span>&nbsp;
              <span class="pull-right label label-primary info-label">
                {{ $filter.optionKVArray($Enums.COURSE_STATUS_ARRAY, course.status) }}
              </span>
            </div>
            <h3 class="search-title">
              <a href="#" class="blue">{{ course.name }}</a>
            </h3>
            <p>
              <span class="blue bolder bigger-150">
                {{ course.price }}&nbsp;<i class="fa fa-rmb"></i>
              </span>
            </p>
            <p>{{ course.summary }}</p>
            <p>
              <span class="badge badge-info">{{ course.id }}</span>&nbsp;
              <span class="badge badge-info">排序: {{ course.sort }}</span>&nbsp;
              <span class="badge badge-info">时长: {{ $filter.formatSecond(course.time) }}</span>
            </p>
            <p>
              <button class="btn btn-xs btn-info" @click="toChapter(course)">
                大章
              </button>&nbsp;
              <button class="btn btn-xs btn-info" @click="editContent(course)">
                内容
              </button>&nbsp;
              <button class="btn btn-xs btn-info" @click="openSortModal(course)">
                排序
              </button>&nbsp;
              <button class="btn btn-xs btn-info" @click="edit(course)">
                编辑
              </button>&nbsp;
              <button class="btn btn-xs btn-danger" @click="del(course.id)">
                删除
              </button>
            </p>
          </div>
        </div>
      </div>
    </div>
    <!-- 弹窗 -->
    <div id="form-modal" class="modal fade" tabindex="-1" role="dialog">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                aria-hidden="true">&times;</span></button>
            <h4 class="modal-title">表单</h4>
          </div>
          <div class="modal-body">
            <form class="form-horizontal">
              <div class="form-group">
                <label class="col-sm-2 control-label">
                  分类
                </label>
                <div class="col-sm-10">
                  <ul id="tree" class='ztree'></ul>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">封面</label>
                <div class="col-sm-10">
                  <File v-bind:suffixs="['jpg','jpeg','png']"
                        v-bind:inputId="'image-upload'"
                        v-bind:text="'上传封面'"
                        v-bind:after-upload="afterUpload"
                        v-bind:use="'C'"></File>
                  <div v-show="course.image" class="row">
                    <div class="col-md-6"><img v-bind:src="course.image" class="img-responsive"/></div>
                  </div>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">名称</label>
                <div class="col-sm-10">
                  <input v-model="course.name" type="text" class="form-control">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">讲师</label>
                <div class="col-sm-10">
                  <select v-model="course.teacherId" class="form-control">
                    <option v-for="o in teachers" v-bind:value="o.id">
                      {{ o.name }}
                    </option>
                  </select>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">概述</label>
                <div class="col-sm-10">
                  <input v-model="course.summary" type="text" class="form-control">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">时长</label>
                <div class="col-sm-10">
                  <input v-model="course.time" type="text" class="form-control">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">价格（元）</label>
                <div class="col-sm-10">
                  <input v-model="course.price" type="text" class="form-control">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">级别</label>
                <div class="col-sm-10">
                  <select v-model="course.level" class="form-control">
                    <option v-for="o in $Enums.COURSE_LEVEL" v-bind:value="o.key">
                      {{ o.value }}
                    </option>
                  </select>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">收费</label>
                <div class="col-sm-10">
                  <select v-model="course.charge" class="form-control">
                    <option v-for="o in $Enums.COURSE_CHARGE" v-bind:value="o.key">
                      {{ o.value }}
                    </option>
                  </select>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">状态</label>
                <div class="col-sm-10">
                  <select v-model="course.status" class="form-control">
                    <option v-for="o in $Enums.COURSE_STATUS" v-bind:value="o.key">
                      {{ o.value }}
                    </option>
                  </select>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">报名数</label>
                <div class="col-sm-10">
                  <input v-model="course.enroll" type="text" class="form-control">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">时序</label>
                <div class="col-sm-10">
                  <input v-model="course.sort" type="text" class="form-control" disabled>
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            <button type="button" class="btn btn-primary" @click="save">保存</button>
          </div>
        </div><!-- /.modal-content -->
      </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->
    <!-- 内容编辑   -->
    <div id="course-content-modal" class="modal fade" tabindex="-1" role="dialog">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                aria-hidden="true">&times;</span></button>
            <h4 class="modal-title">内容编辑</h4>
          </div>
          <div class="modal-body">
            <File v-bind:suffixs="['jpg','jpeg','png','mp4']"
                  v-bind:inputId="'content-file-upload'"
                  v-bind:text="'上传文件1'"
                  v-bind:after-upload="afterUploadContentFile"
                  v-bind:use="'C'"></File>
            <br>
            <table id="file-table" class="table table-bordered table-hover">
              <thead>
              <tr>
                <th>名称</th>
                <th>地址</th>
                <th>大小</th>
                <th>操作</th>
              </tr>
              </thead>
              <tbody>
              <tr v-for="(f,i) in files" v-bind:key="f.id">
                <td>{{f.name}}</td>
                <td>{{f.url}}</td>
                <td>{{f.size}}</td>
              </tr>
              </tbody>
            </table>
            <form class="form-horizontal">
              <div class="form-group">
                <div class="col-lg-12">
                  {{ saveContentLabel }}
                </div>
              </div>
              <div class="form-group">
                <div class="col-lg-12">
                  <div id="content"></div>
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-white btn-default btn-round" data-dismiss="modal">
              <i class="ace-icon fa fa-times"></i>
              取消
            </button>
            <button type="button" class="btn btn-white btn-info btn-round" @click="saveContent()">
              <i class="ace-icon fa fa-plus blue"></i>
              保存
            </button>
          </div>
        </div><!-- /.modal-content -->
      </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->
    <!--  排序编辑  -->
    <div id="course-sort-modal" class="modal fade" tabindex="-1" role="dialog">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                aria-hidden="true">&times;</span></button>
            <h4 class="modal-title">排序</h4>
          </div>
          <div class="modal-body">
            <form class="form-horizontal">
              <div class="form-group">
                <label class="control-label col-lg-3">
                  当前排序
                </label>
                <div class="col-lg-9">
                  <input class="form-control" v-model="sort.oldSort" name="oldSort" disabled>
                </div>
              </div>
              <div class="form-group">
                <label class="control-label col-lg-3">
                  新排序
                </label>
                <div class="col-lg-9">
                  <input class="form-control" v-model="sort.newSort" name="newSort">
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-white btn-default btn-round" data-dismiss="modal">
              <i class="ace-icon fa fa-times"></i>
              取消
            </button>
            <button type="button" class="btn btn-white btn-info btn-round" v-on:click="updateSort()">
              <i class="ace-icon fa fa-plus blue"></i>
              更新排序
            </button>
          </div>
        </div><!-- /.modal-content -->
      </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->
  </div>
</template>

<script>
import Pagination from "@/components/pagination";
import File from "@/components/file";

export default {
  components: {Pagination, File},
  name: "course",
  data() {
    return {
      course: {},
      courses: [],
      categorys: [],
      tree: {},
      saveContentLabel: "",
      sort: {
        id: "",
        oldSort: 0,
        newSort: 0
      },
      teachers: []
    }
  },
  props: {
    'activeSidebar': {
      type: Function
    }
  },
  mounted() {
    let _this = this;
    _this.allCategory();
    _this.allTeacher();
    // this.activeSidebar("business-course-sidebar")
    _this.list(1);
  },
  methods: {
    list(page) {
      Loading.show();
      let _this = this;
      _this.$post(process.env.VUE_APP_SERVER + "/business/admin/course/list", {
        page: page,
        size: _this.$refs.pagination.size
      }).then(res => {
        Loading.hide();
        console.log(res);
        let content = res.content;
        _this.courses = content.list;
        _this.$refs.pagination.render(page, content.total);
      }).catch(res => {
        console.log(res);
      });
    },
    add() {
      let _this = this;
      // 让tree的所有节点都不选中
      _this.course = {
        sort: _this.$refs.pagination.total + 1
      };
      _this.tree.checkAllNodes(false);
      $("#form-modal").modal('show');
    },
    save() {
      let _this = this;
      // 保存校验
      if (1 !== 1
          || !Validator.require(_this.course.name, "名称")
          || !Validator.length(_this.course.name, "名称", 1, 50)
          || !Validator.length(_this.course.summary, "概述", 1, 2000)
          || !Validator.length(_this.course.image, "封面", 1, 100)
      ) {
        return;
      }
      let categorys = this.tree.getCheckedNodes();
      _this.course.categorys = categorys;
      if (Tool.isEmpty(categorys)) {
        Toast.warning("请选择分类!");
        return;
      }
      Loading.show();
      _this.$post(process.env.VUE_APP_SERVER + "/business/admin/course/save", _this.course).then(res => {
        Loading.hide();
        console.log(res);
        if (res.success) {
          $("#form-modal").modal('hide');
          _this.list(1);
          Toast.success('保存成功！');
        } else {
          $("#form-modal").modal('hide');
          _this.list(1);
          Toast.success(res.message);
        }
      }).catch(res => {
        console.log(res);
      });
    },
    del(id) {
      let _this = this;
      Confirm.show("删除课程表后不可恢复!", function () {
        Loading.show();
        _this.$get(process.env.VUE_APP_SERVER + "/business/admin/course/del/" + id).then(res => {
          Loading.hide();
          console.log(res);
          if (res.success) {
            Toast.success('删除成功！');
            _this.list(1);
          } else {
            Toast.success('删除失败！');
            _this.list(1);
          }
        }).catch(res => {
          console.log(res);
          Toast.error('删除失败！')
        });
      })
    },
    edit(course) {
      let _this = this;
      _this.course = $.extend({}, course);
      _this.listCategory(course.id);
      $("#form-modal").modal('show');
    },
    // 点击[大章]
    toChapter(course) {
      let _this = this;
      SessionStorage.set(SESSION_KEY_COURSE, course);
      _this.$router.push("/business/chapter")
    },
    // 点击[内容]
    editContent(course) {
      let _this = this;
      _this.course = course;
      let id = course.id;
      $("#content").summernote({
        focus: true,
        height: 300
      });
      // 先清空历史文本
      $("#content").summernote('code', '');
      Loading.show();
      _this.$get(process.env.VUE_APP_SERVER + '/business/admin/course/find-content/' + id).then(res => {
        console.log(res);
        Loading.hide();
        if (res.success) {
          $("#course-content-modal").modal({backdrop: 'static', keyboard: false});
          if (res.content) {
            $("#content").summernote('code', res.content.content);
          }

          // 定时自动保存
          let saveContentInterval = setInterval(function () {
            _this.saveContent();
          }, 5000);

          // 关闭内容框时自动保存
          $('#course-sort-modal').on('hidden.bs.modal', function (e) {
            clearInterval(saveContentInterval)
          });
        } else {
          Toast.warning(res.message);
        }
      });
    },
    allCategory() {
      let _this = this;
      Loading.show();
      _this.$get(process.env.VUE_APP_SERVER + "/business/admin/category/all").then(res => {
        Loading.hide();
        _this.categorys = res.content;
        _this.initTree();
      });
    },
    initTree() {
      let _this = this;
      let setting = {
        check: {
          enable: true
        },
        data: {
          simpleData: {
            idKey: "id",
            pIdKey: "parent",
            rootPId: "00000000",
            enable: true,
          }
        }
      };
      let zNodes = _this.categorys;
      _this.tree = $.fn.zTree.init($("#tree"), setting, zNodes);
    },
    listCategory(courseId) {
      let _this = this;
      Loading.show();
      _this.$post(process.env.VUE_APP_SERVER + "/business/admin/course/list-catrgory/" + courseId).then(res => {
        Loading.hide();
        console.log("123123", res);
        _this.categorys = res.content;
        _this.tree.checkAllNodes(false);
        for (let i = 0; i < _this.categorys.length; i++) {
          let node = _this.tree.getNodeByParam("id", _this.categorys[i].categoryId);
          _this.tree.checkNode(node);
        }
      });
    },
    /**
     * 保存内容
     */
    saveContent() {
      let _this = this;
      let content = $("#content").summernote("code");
      _this.$post(process.env.VUE_APP_SERVER + '/business/admin/course/save-content', {
        id: _this.course.id,
        content: content
      }).then(res => {
        Loading.hide();
        if (res.success) {
          // Toast.success("内容保存成功");
          // let now = Tool.dateFormat("yyyy-MM-dd hh:mm:ss");
          let now = Tool.dateFormat("mm:ss");
          _this.saveContentLabel = "最后保存时间：" + now;
        } else {
          Toast.warning(res.message);
        }
      });
    },
    // 显示排序模态框
    openSortModal(course) {
      let _this = this;
      _this.sort = {
        id: course.id,
        oldSort: course.sort,
        newSort: course.sort
      }
      $("#course-sort-modal").modal("show");
    },
    // 更新排序
    updateSort() {
      let _this = this;
      if (_this.sort.oldSort === _this.sort.newSort) {
        Toast.warning("排序没有发生变化");
        return;
      }
      Loading.show();
      _this.$post(process.env.VUE_APP_SERVER + '/business/admin/course/sort', _this.sort).then(res => {
        Loading.hide();
        if (res.success) {
          Toast.success("更新排序成功");
          $("#course-sort-modal").modal("hide");
          _this.list(1);
        } else {
          Toast.warning(res.message);
        }
      });

    },
    allTeacher() {
      let _this = this;
      Loading.show();
      _this.$get(process.env.VUE_APP_SERVER + "/business/admin/teacher/all").then(res => {
        Loading.hide();
        _this.teachers = res.content;
      });
    },
    afterUpload(res) {
      let _this = this;
      _this.course.image = res.content.path;
    }
  }
}
</script>

<style scoped>
.caption h3 {
  font-size: 20px;
}
</style>